package pers.gxm.security.hello.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import pers.gxm.security.hello.common.R;
import pers.gxm.security.hello.pojo.LoginUser;
import pers.gxm.security.hello.pojo.User;
import pers.gxm.security.hello.service.LoginService;
import pers.gxm.security.hello.utils.JwtUtil;
import pers.gxm.security.hello.utils.RedisCache;

import java.util.HashMap;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Override
    public R login(User user) {
//        TODO 1    登录认证，需要在容器中注入AuthenticationManager
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
//       在这里将数据库的用户数据封装到Authentication中
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);

//        TODO 1.1  需要判断认证结果是否为空
            if(authenticate == null){
                throw new RuntimeException("登录失败!");
            }

//        TODO 2    将id生成jwt返回给前端
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String id = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(id);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",jwt);

//        TODO 3    缓存到redis
        redisCache.setCacheObject("login"+id,loginUser);
        return R.successWithMsgAndData(200,"登录成功",map);
    }

    @Override
    public R logout() {
//        TODO  1   获取SecurityContextHolder中的Authentication
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        TODO  2   再获取当中封装的LoginUser
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        TODO  3   获取UserId,并且到redis中删除
        String redisKey = "login" + loginUser.getUser().getId();
        redisCache.deleteObject(redisKey);
        return R.successWithMsg(200,"注销成功!");
    }
}
